package com.mall.b2c.interceptor;

import static com.mall.b2c.Constants.LOGIN_MEMBER_USERNAME_COOKIE_NAME;
import static com.mall.b2c.Constants.PRINCIPAL_SESSION_NAME;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mall.b2c.bean.Principal;
import com.mall.common.util.AppContext;
import com.mall.common.util.CookieUtils;


/**
 * 登陆验证拦截器
 *
 */
public class MemberLoginVerifyInterceptor implements HandlerInterceptor {
	public static final String loginUrl = "/login.jhtml";

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Principal principal = (Principal)AppContext.getSessionAttr(PRINCIPAL_SESSION_NAME);
		if(principal != null){
			return true;
		}
		CookieUtils.removeCookie(request, response, LOGIN_MEMBER_USERNAME_COOKIE_NAME);
		if (AppContext.isAjax(request)) {
			response.addHeader("loginStatus", "accessDenied");
			response.sendError(403);
			return false;
		}
		if (request.getMethod().equalsIgnoreCase("GET")){
			String s1 = request.getRequestURL().toString();
			Object oldUrl = request.getAttribute("oldUrl");
			if(oldUrl != null){
				s1 = oldUrl.toString();
			}
			if(request.getQueryString() != null){
				s1 = s1 + "?" + request.getQueryString().toString();
			}
			
			response.sendRedirect(new StringBuffer("/login.jhtml?")
					.append("redirectUrl").append("=").append(URLEncoder.encode(s1, "UTF-8")).toString());
		} else {
			response.sendRedirect("/login.jhtml");
		}
		return false;
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		clearCache(response);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
    
	/**
	 * 清除缓存
	 */
	private void clearCache(HttpServletResponse response){
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Cache-Control", "no-store");  
		response.setDateHeader("Expires", 0);
	}

}